package com.github.andy0106.kersstjtl.files;

import java.io.IOException;
import java.nio.file.*;

public class File implements Readable, Writeable {
    private String name;
    private String path;
    private transient Path paths;

    public File(String name, String path) {
        this.name = name;
        this.path = path;
        this.paths = Paths.get(path, name);
    }

    public File(java.io.File file) {
        this(file.getName(), file.getPath());
    }

    public File(Path paths) {
        this(paths.getFileName().toString(), paths.getParent().toString());
    }

    @Override
    public byte[] read() {
        if (!isExists()) return null;
        try {
            return Files.readAllBytes(paths);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public boolean write(byte[] bytes, StandardOpenOption... openOption) {
        if (!isExists()) return false;
        try {
            Files.write(paths, bytes, openOption);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public void create() {
        try {
            Files.createFile(this.paths);
        } catch (IOException e) {
            return;
        }
    }

    public boolean isExists() {
        return Files.isRegularFile(paths);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public Path getPaths() {
        return paths;
    }

    public void setPaths(Path paths) {
        this.paths = paths;
    }

    public boolean rename(String new_name) {
        Path new_path = Paths.get(path, new_name);
        if (!isExists()) return false;
        if (Files.exists(new_path)) return false;
        try {
            Files.copy(paths, new_path);
            Files.delete(paths);
            setName(new_name);
            setPaths(new_path);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return paths.toString();
    }
}
